// function main() {
//     console.log('----start-----');
//     // while (true) {
//     //     if (text('立即购买').clickable().exists()) {
//     //         text('立即购买').clickable().findOne(1000).click()
//     //     }

//     //     if (id('com.taobao.taobao:id/body').className('android.support.v7.widget.RecyclerView').exists()) {
//     //         let body = id('com.taobao.taobao:id/body').className('android.support.v7.widget.RecyclerView').findOne(1000)
//     //         console.log(body);
//     //     }

//     // }

// // let nodeMap = {
// //     '颜色出售': {
// //         '白色': node
// //     },
// //     '尺码': {
// //         '36': node
// //     }
// // }

//     // 未选择的种类
//     let chs = textContains('选择').findOne(1000)
//     if (!chs) {
//         return
//     }
//     let chooses = chs.text().replace(',', ' ').split(/\s/).slice(1)

//     let title = chooses[0]
//     // 种类标题的深度
//     let tDepth = textStartsWith(chooses[0]).findOne(1000).depth()
//     console.log(title,tDepth);

//     // 界面所有text长度大于1的节点
//     let textNodes = auto.root.find(textMatches(/.+/))
//     for (let i = 0; i < textNodes.length; i++) {
//         let node = textNodes[i] // 节点
//         let nodeText = node.text() // 节点文本
//         let depth = node.depth() // 节点深度

//         if (nodeText == '购买数量') {
//             break
//         }
//         // console.log(depth + '  '+ nodeText);

//         if (depth == tDepth) {
//             title = nodeText.replace(/\(.*?\)/,'')
//             nodeTree[title] = {}
//             console.log(title);
//         } else if (depth > tDepth) {
//             try {
//                 nodeTree[title][nodeText] = node
//             } catch (err) {

//             }
//         }
//     }

//     // for (let i = 0; i < chooses.length; i++) {
//     //     let title = chooses[i];
//     //     log(title)
//     //     mClick(title,'白色')
//     // }
//     mClick('颜色分类', '白色')
//     sleep(10)
//     mClick('尺码','36')
//     console.log('----end-----');
// }

// // 节点树
// let nodeTree = {}
// function mClick(title, choose) {
//     let nodes = nodeTree[title]
//     for (let name in nodes) {
//         if (name.indexOf(choose) != -1) {
//             nodes[name].parent().click()
//             nodes[name].parent().parent().parent().click()
//             return
//         }
//     }
// }

'ui';

auto.setWindowFilter(function (window) {
	return window.title == '手机淘宝xx'
	// return true
})

let chooses = []
let storage = storages.create('tao')
// storage.clear()

let ch1 = storage.get('ch1', '')
let ch2 = storage.get('ch2', '')
let ch3 = storage.get('ch3', '')

// 脚本运行线程
let workThread = null
// 脚本运行状态
let isRunning = false
// 悬浮窗口
let wd = null

events.on('exit', function () {
	storage.put('ch1', ch1)
	storage.put('ch2', ch2)
	storage.put('ch3', ch3)
})

function showFloaty() {
	wd = floaty.rawWindow(
		<vertical w="*" h="*">
			<frame layout_weight="1" h="30" layout_gravity="center">
				<img
					w="*"
					h="30"
					src="#ffffff"
					borderWidth="1dp"
					scaleType="fitXY"
					circle="true"
				/>
				<text
					id="start"
					h="30"
					text="开始运行"
					textSize="12sp"
					gravity="center"
					padding="15 0 "
				/>
			</frame>
			<frame h="30" layout_weight="1" layout_gravity="center" marginTop="2">
				<img
					w="*"
					h="30"
					src="#ffffff"
					borderWidth="1dp"
					scaleType="fitXY"
					circle="true"
				/>
				<text
					id="stop"
					h="30"
					text="结束运行"
					textSize="12sp"
					gravity="center"
					padding="15 0"
				/>
			</frame>
		</vertical>
	)
	wd.setPosition(20, device.height / 5)
	wd.exitOnClose()
	wd.stop.on('click', function () {
		isRunning = false
		if (workThread) {
			workThread.interrupt()
			workThread = null
		}
		toastLog('运行结束')
		exit()
	})
	wd.start.on('click', function () {
		//程序开始运行之前判断无障碍服务
		if (!auto.service) {
			toast('请先开启无障碍服务！')
			app.startActivity({
				action: 'android.settings.ACCESSIBILITY_SETTINGS',
			})
			return
		}

		if (isRunning) {
			toastLog('运行暂停')
			isRunning = false
			ui.run(function () {
				wd.start.setText('开始运行')
			})
			// threads.shutDownAll()
			return
		}

		if (ch1.length != 0) {
			chooses.push(ch1)
		}
		if (ch2.length != 0) {
			chooses.push(ch2)
		}
		if (ch3.length != 0) {
			chooses.push(ch3.split(/\s+/))
		}

		isRunning = true
		ui.run(function () {
			wd.start.setText('暂停运行')
		})

		if (!workThread) {
			workThread = threads.start(function () {
				toastLog('运行开始')
				app.launchPackage('com.taobao.taobao')
				while (true) {
					while (!isRunning) {}
					try {
						main()
					} catch (error) {}
				}
			})
		}
	})
}

threads.start(function () {
	// 	// // 检测是否打开无障碍权限
	// 	// if (!floaty.checkPermission()) {
	// 	// 	floaty.requestPermission()
	// 	// 	exit()
	// 	// }
	// 	// sleep(1000)
	showFloaty()
})

ui.statusBarColor('#40a5f3')
ui.layout(
	<vertical>
		<appbar bg="#40a5f3">
			<toolbar id="title" title="淘宝抢鞋" />
		</appbar>
		<Switch
			id="floatx"
			text="悬浮窗权限"
			checked="{{floaty.checkPermission()}}"
			padding="8 8 8 8"
			textSize="15sp"
			gravity="right"
		/>
		<Switch
			id="autoService"
			text="无障碍服务"
			checked="{{auto.service != null}}"
			padding="8 8 8 8"
			textSize="15sp"
			gravity="right"
		/>
		<vertical marginTop="30" paddingRight="40dp">
			<horizontal w="*" gravity="center">
				<text textSize="14sp" text="尺码" />
				<input
					w="100dp"
					gravity="center"
					textSize="14sp"
					id="ch1"
					text="{{ch1}}"
				/>
			</horizontal>
			<horizontal w="*" gravity="center">
				<text textSize="14sp" text="颜色" />
				<input
					w="100dp"
					gravity="center"
					textSize="14sp"
					id="ch2"
					text="{{ch2}}"
				/>
			</horizontal>
			<horizontal w="*" gravity="center">
				<text textSize="14sp" text="其他" />
				<input
					w="100dp"
					gravity="center"
					textSize="14sp"
					id="ch3"
					text="{{ch3}}"
				/>
			</horizontal>
		</vertical>
	</vertical>
)

ui.ch1.addTextChangedListener({
	afterTextChanged: function (content) {
		content = content.toString().trim()
		ch1 = content
	},
})
ui.ch2.addTextChangedListener({
	afterTextChanged: function (content) {
		content = content.toString().trim()
		ch2 = content
	},
})
ui.ch3.addTextChangedListener({
	afterTextChanged: function (content) {
		content = content.toString().trim()
		ch3 = content
	},
})

ui.floatx.on('click', function (checked) {
	floaty.requestPermission()
})
ui.autoService.on('check', function (checked) {
	// 用户勾选无障碍服务的选项时，跳转到页面让用户去开启
	if (checked && auto.service == null) {
		app.startActivity({
			action: 'android.settings.ACCESSIBILITY_SETTINGS',
		})
	}
	if (!checked && auto.service != null) {
		auto.service.disableSelf()
	}
})

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on('resume', function () {
	// 此时根据无障碍服务的开启情况，同步开关的状态
	ui.floatx.checked = floaty.checkPermission()
	ui.autoService.checked = auto.service != null
})

ui.emitter.on('back_pressed', function (event) {
	if (workThread && workThread.isAlive()) {
		event.consumed = true
	}
})

function mClick(choose) {
	if (textContains(choose).exists()) {
		textContains(choose).findOnce().parent().click()
		textContains(choose).findOnce().parent().parent().click()
		textContains(choose).findOnce().parent().parent().parent().click()
	}
}

function main() {
	if (textStartsWith('确').visibleToUser().exists()) {
		for (let i = 0; i < chooses.length; i++) {
			let choose = chooses[i]
            mClick(choose)
        }
        try {
            textStartsWith('确').visibleToUser().findOnce().parent().click()
        } catch (error) {
            
        }
        try {
            textStartsWith('确').visibleToUser().findOnce().parent().child(0).click()
        } catch (error) {
            
        }
        try {
            textStartsWith('确').visibleToUser().findOnce().parent().parent().click()
        } catch (error) {
            
        }
        
		
	}
	if (textContains('立即').exists()) {
		textContains('立即').clickable().visibleToUser().findOnce().click()
	}

	if (text('提交订单').exists()) {
		text('提交订单').clickable().findOnce().click()
	}
}
